//
//  PYSystemTool.m
//  IHome
//
//  Created by Jim on 2019/3/16.
//  Copyright © 2019 com.zhujizheng. All rights reserved.
//

#import "PYSystemTool.h"
#import <Photos/Photos.h>
#import "DeviceDataLibrery.h"

#pragma mark - 堆栈信息
#include <libkern/OSAtomic.h>
#include <execinfo.h>

@interface PYImagePickerController : UIImagePickerController

@end
@implementation PYImagePickerController

#pragma mark - MLeaksFinder methods
- (BOOL)willDealloc {
    return NO;
}

#pragma mark - 屏幕旋转
- (BOOL)shouldAutorotate
{
    return [PYScreenRotateManager shouldAutorotate];
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    if ([PYScreenRotateManager supportedInterfaceOrientations] == UIInterfaceOrientationMaskPortrait) {
        [UIApplication sharedApplication].statusBarOrientation = [PYScreenRotateManager statusBarOrientation];
    }
    return [PYScreenRotateManager supportedInterfaceOrientations];
}
/// 实现这个方法，解决导航栏问题,present
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return [PYScreenRotateManager statusBarOrientation];
}

@end

@interface PYSystemTool () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) UIImagePickerController *imgPickerC;
@property (nonatomic, copy) void (^imgBlock)(UIImage *image);
// 测试代码运行时间
@property (nonatomic, assign) NSTimeInterval beginTime;
@property (nonatomic, assign) NSTimeInterval endTime;
@end

@implementation PYSystemTool

+ (instancetype)shareInstance
{
    static PYSystemTool *tool = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tool = [PYSystemTool new];
    });
    return tool;
}

#pragma mark - 系统版本
+ (BOOL)isBelowSystemVersion:(CGFloat)systemVersion
{
    return UIDevice.currentDevice.systemVersion.floatValue < systemVersion;
}

+ (BOOL)isAboveSystemVersion:(CGFloat)systemVersion
{
    return UIDevice.currentDevice.systemVersion.floatValue >= systemVersion;
}

#pragma mark - 设备类型
+ (BOOL)isIPhoneXOrLater
{
    BOOL result = NO;
    if (UIDevice.currentDevice.userInterfaceIdiom != UIUserInterfaceIdiomPhone) {
        return result;
    }
    if (@available(iOS 11.0, *)) {
        UIWindow *mainWindow = [[[UIApplication sharedApplication] delegate] window];
        if (mainWindow.safeAreaInsets.bottom > 0.0) {
            result = YES;
        }
    }
    return result;
}

+ (BOOL)isIPad
{
    return UIUserInterfaceIdiomPad == UI_USER_INTERFACE_IDIOM();
}

+ (BOOL)isIPhone
{
    return UIUserInterfaceIdiomPhone == UI_USER_INTERFACE_IDIOM();
}

+ (BOOL)isSimulator
{
    return TARGET_IPHONE_SIMULATOR;
}

+ (void)showSimulatorAlert:(nullable NSString *)message
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertController addAction:okAction];
    [PYSystemTool presentViewController:alertController];
}
/** 获取设备名称 */
+ (const NSString *)getDiviceName
{
    return [[DeviceDataLibrery sharedLibrery] getDiviceName];
}
/** 获取设备电池容量，单位 mA 毫安 */
+ (NSInteger)getBatteryCapacity
{
    return [[DeviceDataLibrery sharedLibrery] getBatteryCapacity];
}
/** 获取电池电压，单位 V 福特 */
+ (CGFloat)getBatterVolocity
{
    return [[DeviceDataLibrery sharedLibrery] getBatterVolocity];
}
/** 获取CPU处理器名称 */
+ (const NSString *)getCPUProcessor
{
    return [[DeviceDataLibrery sharedLibrery] getCPUProcessor];
}
#pragma mark - 状态栏
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+ (void)showDefaultStatus
{
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

+ (void)showLightStatus
{
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}

+ (void)showDefaultStatusWithAnimation
{
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    if ([UIApplication sharedApplication].isStatusBarHidden) {
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
    }
}

+ (void)showLightStatusWithAnimation
{
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    if ([UIApplication sharedApplication].isStatusBarHidden) {
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
    }
}

+ (void)hideStatusWithAnimation
{
    if ([UIApplication sharedApplication].isStatusBarHidden == NO) {
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
    }
}

/// 隐藏状态栏，不带动画
+ (void)hideStatus
{
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
}
/// 显示状态栏，不带动画
+ (void)showStatus
{
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
}
#pragma clang diagnostic pop

#pragma mark - 设备方向
+ (void)rotateDeviceToOrientation:(UIDeviceOrientation)deviceOrientation
{
    [[UIDevice currentDevice] setValue:@(deviceOrientation) forKey:@"orientation"];
}

#pragma mark - 判断系统时间是不是24小时制
+ (BOOL)is24Hour
{
    NSLocale *locale = [NSLocale currentLocale];
    NSString *formatStringForHours = [NSDateFormatter dateFormatFromTemplate:@"j" options:0 locale:locale];
    NSRange containsA = [formatStringForHours rangeOfString:@"a"];
    return containsA.location == NSNotFound;
}

#pragma mark - 开发中
+ (void)showDevelopingAlert
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"此功能尚未开发" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController];
}

#pragma mark - 时间
/// 获取当前系统时间，精度为毫秒
+ (long)systemTime
{
    return (long)([[NSDate date] timeIntervalSince1970] * 1000);
}

#pragma mark - 测试代码运行时间
/// 开始测试
+ (void)beginTest
{
    [PYSystemTool shareInstance].beginTime = [[NSDate date] timeIntervalSince1970];
    NSLog(@"开始测试");
}
/// 结束测试，并打印代码运行时间
+ (void)endTest
{
    PYSystemTool *tool = [PYSystemTool shareInstance];
    tool.endTime = [[NSDate date] timeIntervalSince1970];
    NSLog(@"测试结束，代码运行时间:%f毫秒", (tool.endTime - tool.beginTime) * 1000);
}

#pragma mark - App是否从TestFlight、AppStore下载
/// YES 从TestFlight下载，NO 不是从TestFlight下载
+ (BOOL)isAppFromTestFlight
{
    return [self isAppStoreReceiptSandbox] && ![self hasEmbeddedMobileProvison];
}
/// YES 从AppStore下载，NO 不是从AppStore下载
+ (BOOL)isAppFromAppStore
{
    if ([self isAppStoreReceiptSandbox] || [self hasEmbeddedMobileProvison]) {
        return NO;
    }
    return YES;
}
+ (BOOL)isAppStoreReceiptSandbox
{
    return [[[[NSBundle mainBundle] appStoreReceiptURL] lastPathComponent] isEqualToString:@"sandboxReceipt"];;
}
+ (BOOL)hasEmbeddedMobileProvison
{
    return [[NSBundle mainBundle] pathForResource:@"embedded" ofType:@"mobileprovision"] != nil;
}

/// 获取App名字
+ (NSString *)getAppName
{
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
}
/// 获取App版本号
+ (NSString *)getAppVersion
{
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
}
/// 获取Appid
+ (NSString *)getAppID
{
    return @"1459143052";
}
/// 更新App
+ (void)updateApp:(NSString *)appDownloadUrl
{
    NSLog(@"更新app，appDownloadUrl：%@", appDownloadUrl);
    if (!appDownloadUrl) {
        return;
    }
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appDownloadUrl] options:@{} completionHandler:nil];
    } else {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appDownloadUrl]];
    }
}
/// 蒲公英更新
+ (void)updateAppFromDandelion
{
    NSLog(@"蒲公英更新");
    NSString *url = @"https://www.pgyer.com/apiv2/app/builds";
    NSString *apiKey = @"7a9dd062078f9a189052c244927d8462";
    NSString *appKey = @"1901a0902e2a371e90faa0e25bf3a1db";
//    NSString *appKey = @"c7cee421a547a4dfb5218eda3b3f4d36";
    NSDictionary *param = @{@"appKey":appKey, @"_api_key":apiKey};
    [PYHttp requestWithURLString:url parameters:param requestType:PY_POST bodyType:PY_Form_Data success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        if (![responseObject isKindOfClass:[NSDictionary class]]) {
            return ;
        }
        NSDictionary *data = [responseObject objectForKey:@"data"];
        if (![data isKindOfClass:[NSDictionary class]]) {
            return ;
        }
        NSArray *list = [data objectForKey:@"list"];
        if (![list isKindOfClass:[NSArray class]]) {
            return;
        }
        NSDictionary *dict = [list firstObject];
        if (![dict isKindOfClass:[NSDictionary class]]) {
            return;
        }
        NSString *buildKey = [dict stringValueForKey:@"buildKey" default:nil];
        if (buildKey) {
            NSString *appDownloadUrl = [NSString stringWithFormat:@"itms-services://?action=download-manifest&url=https://www.pgyer.com/app/plist/%@", buildKey];
            [PYSystemTool updateApp:appDownloadUrl];
        }
    } failure:nil];
}
#pragma mark - 跳转到其他应用
+ (void)gotoTestFlight
{
    NSLog(@"跳转到TestFlight更新");
    NSURL *testFlightAppURL = [NSURL URLWithString:@"itms-beta://"];
    if ([[UIApplication sharedApplication] canOpenURL:testFlightAppURL]) {
        NSString *appUrlString = [NSString stringWithFormat:@"https://beta.itunes.apple.com/v1/app/%@", [PYSystemTool getAppID]];
        NSURL *appURL = [NSURL URLWithString:appUrlString];
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:appURL options:@{} completionHandler:nil];
        } else {
            [[UIApplication sharedApplication] openURL:appURL];
        }
    } else {
        NSURL *appURL = [NSURL URLWithString:@"https://itunes.apple.com/us/app/testflight/id899247664?mt=8"];
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:appURL options:@{} completionHandler:nil];
        } else {
            [[UIApplication sharedApplication] openURL:appURL];
        }
    }
}

+ (void)gotoAppStore
{
    NSLog(@"跳转到AppStore");
}

+ (void)gotoSystemSetting
{
    NSLog(@"跳转到系统设置");
    NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([[UIApplication sharedApplication] canOpenURL:settingURL]) {
        // 跳转到系统设置
        [[UIApplication sharedApplication] openURL:settingURL options:@{} completionHandler:nil];
    }
}

#pragma mark - 堆栈信息
+ (void)logStackInfo
{
    void* callstack[128];
    int frames = backtrace(callstack, 128);
    char **strs = backtrace_symbols(callstack, frames);
    int i;
    NSMutableArray *backtrace = [NSMutableArray arrayWithCapacity:frames];
    for (i = 0;i < 4;i++){
        [backtrace addObject:[NSString stringWithUTF8String:strs[i]]];
    }
    free(strs);
    NSLog(@"=====>>>>>堆栈<<<<<=====\n%@",backtrace);
    NSArray *csss = [NSThread callStackSymbols];
    NSLog(@"=====>>>>>堆栈<<<<<=====\n%@",csss);
}

#pragma mark - 打印所有苹果自带字体
+ (void)printAllAppleFont
{
    NSArray *familyNames = [UIFont familyNames];
    for(NSString *familyName in familyNames)
    {
        NSLog(@"%@", familyName);
        NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName];
        for(NSString *fontName in fontNames)
        {
            NSLog(@"\t%@", fontName);
        }
    }
}

#pragma mark - 生成钱格式的字符串
+ (NSString *)generateMoneyStringWithDecimalNumber:(NSDecimalNumber *)decimalNumber
{
    NSDecimalNumber *number = [decimalNumber decimalNumberByMultiplyingBy:[NSDecimalNumber decimalNumberWithString:@"100"]];
    
    NSInteger integer = [number integerValue];
    integer = labs(integer);
    NSInteger wan = integer / 1000000;
    NSInteger wanRemain = integer % 1000000;
    NSInteger num = wanRemain / 100;
    NSInteger decimal = wanRemain % 100;
    NSString *decimalStr = @"";
    do {
        // 小数位为0
        if (decimal == 0) {
            decimalStr = @".0";
            break;
        }
        // 小数位只有一位
        if (decimal < 10) {
            decimalStr = [NSString stringWithFormat:@".%02ld", (long)decimal];
            break;
        }
        // 小数位有两位
        NSInteger decimalRemain = decimal % 10;
        if (decimalRemain == 0) {
            decimalStr = [NSString stringWithFormat:@".%ld", (long)(decimal / 10)];
        } else {
            decimalStr = [NSString stringWithFormat:@".%02ld", (long)decimal];
        }
    } while (0);
    // 金额超过一万
    if (wan > 0) {
        return [NSString stringWithFormat:@"%@%ld,%04ld%@", number.integerValue < 0 ? @"-" : @"", (long)wan, (long)num, decimalStr];
    }
    // 金额低于一万
    return [NSString stringWithFormat:@"%@%ld%@", number.integerValue < 0 ? @"-" : @"", (long)num, decimalStr];
}

#pragma mark - MLeaksFinder methods
- (BOOL)willDealloc {
    return NO;
}
@end
